package com.system.enterprisemanagementsystem.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.system.enterprisemanagementsystem.exception.BusinessException;
import com.system.enterprisemanagementsystem.mapper.ClazzMapper;
import com.system.enterprisemanagementsystem.pojo.Clazz;
import com.system.enterprisemanagementsystem.pojo.ClazzQueryParam;
import com.system.enterprisemanagementsystem.pojo.Emp;
import com.system.enterprisemanagementsystem.pojo.PageResult;
import com.system.enterprisemanagementsystem.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;
@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    ClazzMapper clazzMapper;

    @Override
    public PageResult page(ClazzQueryParam clazzQueryParam) {
        // 1. 设置分页参数
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());

        // 2. 执行查询
        List<Clazz> clazzList = clazzMapper.list(clazzQueryParam);

        // 3. 遍历结果，根据时间计算状态并设置
        LocalDate now = LocalDate.now();
        for (Clazz clazz : clazzList) {
            LocalDate beginDate = clazz.getBeginDate();
            LocalDate endDate = clazz.getEndDate();

            String status;
            if (now.isAfter(endDate)) {
                status = "已结课";
            } else if (now.isBefore(beginDate)) {
                status = "未开班";
            } else {
                status = "在读中";
            }

            clazz.setStatus(status);
        }

        // 4. 封装分页结果
        Page<Clazz> p = (Page<Clazz>) clazzList;
        return new PageResult(p.getTotal(), p.getResult());
    }

    @Override
    public List<Clazz> clazzList( ) {
        return clazzMapper.selectAll();
    }

    @Override
    public void addClazz(Clazz clazz) {
        clazzMapper.addClazz(clazz);
    }

    @Override
    public Clazz queryClazzById(int id) {
        return  clazzMapper.getClazzById(id);

    }

    @Override
    public void updateClazz(Clazz clazz) {

        clazzMapper.updateClazz(clazz);

    }

    @Override
    @Transactional
    public void deleteClazzById(int id) {
        // 直接删除，通过返回值判断是否成功
        int affectedRows = clazzMapper.deleteClazzById(id);
        if (affectedRows == 0) {
            throw new BusinessException("删除失败，班级可能不存在或已被删除");
        }
    }

    @Override
    public Integer getStudentCountByClazzId(Integer clazzId) {
        return  clazzMapper.getStudentCountByClazzId(clazzId);

    }

}
